const router = require('koa-router')()
const users = require('./users')
const login = require('./login')
const list = require('./list')
const recommend = require('./recommend')
const upload = require('./upload')

class RouterStore{

  constructor(preRouter){
    this._store = {};
    this.preRouter = preRouter;
  }

  add(path, route){
    if(!this.has(path, true)){
      this._store[path] = route;
      this.bind(path,route);
    }
  }

  bind(path,router){
    this.preRouter.use(path, router.routes(), router.allowedMethods())
  }

  has(path, remind=false){
    let paths = new Set(Object.keys(this._store));
    let status = paths.has(path);
    if(status && remind){
      throw new Error(`💥path: '${path}' had registed !!!`)
    }
    return status;
  }
  
}

router.get('/', async (ctx, next) => {
  ctx.body=`
    <h1>
      Welcome to Koa2 !!!
    </h1>
  `
})


// Routers
const routeStore = new RouterStore (router);

routeStore.add('/users', users);
routeStore.add('/login', login);
routeStore.add('/lists', list);
routeStore.add('/recommend', recommend);
routeStore.add('/upload', upload);

module.exports = {
  router,
  routeStore
}
